import {
  ADDCOMMENT,
  SETARTICLEDETAIL,
  TOGGLELIKED,
  UPDATEARTICLEINFO,
  UPDATECOMMENTCOUNT,
  UPDATECOMMENTSRESULTS
} from "@/store/actionTypes";

const initState = {
  detail: {}, // 获取文章详情数据
  comment: {
    // last_id end_id
    results: [] // 存储的是当前文章的评论信息
  }
}

const articleReducer = (state = initState, action) => {
  // 监听写入文章的action
  switch (action.type) {
    case SETARTICLEDETAIL:
      return {
        ...state,
        detail: action.payload
      }
    case UPDATEARTICLEINFO:
      return {
        ...state,
        detail: {
          ...state.detail,
          [action.payload.name]: action.payload.value
        }
      }

    case UPDATECOMMENTSRESULTS:
      return {
        ...state,
        comment: {
          ...state.comment,
          ...action.payload,
          results: [
            ...state.comment.results,
            ...action.payload.results
          ]
        }
      }

    case ADDCOMMENT:
      return {
        ...state,
        comment: {
          ...state.comment,
          total_count: state.comment.total_count + 1,
          results:[
            action.payload,
            ...state.comment.results,
          ]
        }
      }

    case TOGGLELIKED:
      return {
        ...state,
        comment: {
          ...state.comment,
          results: state.comment.results.map(item => {
            if (item.com_id === action.payload.target) {
              return {
                ...item,
                [action.payload.name]: action.payload.value, // 切换当前评论的点赞状态
                like_count: action.payload.like_count + item.like_count
              }
            }
            return item
          })
        }
      }

    case UPDATECOMMENTCOUNT:
      return {
        ...state,
        comment: {
          ...state.comment,
          results: state.comment.results.map(item => {
            console.log(action.payload)
            if (item.com_id === action.payload.id) {
              return {
                ...item,
                reply_count: action.payload.total
              }
            }
            return item
          })
        }
      }
    default:
      return state
  }
}

export default articleReducer
